import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';

// 守卫
@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private Reflector: Reflector) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const req = context.switchToHttp().getRequest<Request>(); // 获取请求信息
    const admin = this.Reflector.get('roles', context.getHandler()); // 获取接口设置的元信息， 通过SetMetaData装饰器设置，参数是key, value,通过Reflector获取元信息
    if (admin.includes(req.query.role)) {
      return true;
    } else {
      return false;
    }
  }
}
